package org.wutopia.leocloud.domain.security.resource;


import com.nimbusds.jose.JOSEException;
import jakarta.validation.Valid;
import jakarta.ws.rs.core.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.wutopia.leocloud.domain.security.domain.AuthenticationService;
import org.wutopia.leocloud.domain.security.domain.client.AccountServiceClient;
import org.wutopia.leocloud.domain.security.resource.vo.AuthenticationResourceLoginInputVO;
import org.wutopia.leocloud.domain.security.resource.vo.AuthenticationResourceLoginOutputVO;
import org.wutopia.leocloud.domain.security.resource.vo.AuthenticationResourceLogoutVO;
import org.wutopia.leocloud.domain.security.utility.JwtUtility;
import org.wutopia.leocloud.library.common.domain.account.Account;
import org.wutopia.leocloud.library.common.domain.security.Role;

import javax.security.auth.login.LoginException;
import java.util.ArrayList;
import java.util.List;


@RestController
public class AuthenticationResource {


    @Autowired
    private AccountServiceClient accountServiceClient;

    @Autowired
    private PasswordEncoder passwordEncoder;


    @PostMapping("/login")
    public AuthenticationResourceLoginOutputVO login(@RequestBody @Valid AuthenticationResourceLoginInputVO loginVO) throws Exception {

        Account user = accountServiceClient.getUser(loginVO.getUsername());

        if(!passwordEncoder.matches(loginVO.getPassword(), user.getPassword())) {
            throw new Exception("账号或者密码不正确");
        }


        List<String> authorities = new ArrayList<>();

        authorities.add(Role.USER);

        if (user.getId() == 1) {
            // 由于没有做用户管理功能，默认给系统中第一个用户赋予管理员角色
            authorities.add(Role.ADMIN);
        }

        AuthenticationResourceLoginOutputVO outputVO = new AuthenticationResourceLoginOutputVO();

        outputVO.setUsername(user.getUsername());

        outputVO.setExpiresIn(JwtUtility.EXPIRES_IN);

        outputVO.setAuthorities(authorities);

        outputVO.setTokenType(JwtUtility.TOKEN_TYPE);

        outputVO.setAccessToken(JwtUtility.generateToken(user.getUsername(), authorities));

        outputVO.setRefreshToken(JwtUtility.generateRefreshToken(user.getId().toString()));


        return outputVO;
    }



    @GetMapping("/logout")
    public Response logout(AuthenticationResourceLogoutVO loginVO) {


        return null;
    }
}
